﻿Shader "SongShaderDemo/CutOffObject"
{
	Properties
	{
	   _MainTex("Texture", 2D) = "white" {}
	   _zCutOff("切割范围：",Range(0,1)) = 0
	  _CutDirection("切割方向",Vector) = (0, 0, 0, 0)
	  _CutDistance("切割距离",Float) = 1000
	}
		SubShader
	   {
		   Tags { "RenderType" = "Opaque" "LigthMode" = "ForwarBase"}
		   LOD 100
		  // Blend SrcAlpha OneMinusSrcAlpha

		ZWrite On
		Pass
		{
		Cull Off
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag

			#include "UnityCG.cginc"
			#include "Lighting.cginc "

			struct appdata
			{
				float4 vertex : POSITION;
				float2 uv : TEXCOORD0;
				float3 normal: NORMAL;//存储法线的盒子
			};

			struct v2f
			{
				float2 uv : TEXCOORD0;
				float4 vertex : SV_POSITION;
				float3  worldPos  : TEXCOORD1;
				float3 center:TEXCOORD2;
				float3 wNormal:TEXCOORD6;
			};

			sampler2D _MainTex;
			float4 _MainTex_ST;
			float _zCutOff;
			float _CutDistance;
			float4 _CutDirection;
			v2f vert(appdata v)
			{
				v2f o;
				o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
				//得到中心点
				o.center = float3(unity_ObjectToWorld[0].w, unity_ObjectToWorld[1].w, unity_ObjectToWorld[2].w);
				o.vertex = UnityObjectToClipPos(v.vertex);
				o.uv = TRANSFORM_TEX(v.uv, _MainTex);
				o.wNormal = UnityObjectToWorldNormal(v.normal);
				return o;
			}

			fixed4 frag(v2f i) : SV_Target
			{
				//_WorldSpaceLightPos0 unity提供的灯光向量
				float3 L = normalize(_WorldSpaceLightPos0);
				float3 N = normalize(i.wNormal);
				float halfLam = dot(L, N)*0.5 + 0.75;
				//_LightColor0.rgb unity提供的灯光强度
				float3 diffLight = halfLam * _LightColor0.rgb;
				fixed4 diffColor = fixed4(diffLight.rgb, 1);
				// sample the texture
				fixed4 col = tex2D(_MainTex, i.uv);

			float3 cutDirection = normalize(_CutDirection.xyz);//切割向量
			float3 curCenter = i.center + (cutDirection*(_zCutOff - 0.5)*_CutDistance);//切割的原点，在切割的向量上移动
			float3 targetVer = i.worldPos - curCenter;//切割原点到模型点上的向量
			float angel = dot(normalize(targetVer), cutDirection);//切割向量和targetVer点乘，正则同方向，父则反方向
			clip(angel);//反方向剔除
	
			return col * diffColor;
			}
			ENDCG
		}
		

	   }
		  Fallback "Transparent/VertexLit"
}
